package main

import "fmt"

func Defer() {
	defer func() {
		println("第一个 defer")
	}()

	defer func() {
		println("第二个 defer")
	}()
}

// 后进先出    逻辑栈
// output :
/**
第二个 defer
第一个 defer
*/

func DeferClosure() {
	i := 0
	defer func() {
		println(i)
	}()
	i += 1
}

func DeferClosureV1() {
	i := 0
	defer func(val int) {
		println(val)
	}(i)
	i = 1
}

func DeferReturn() int {
	a := 0
	defer func() {
		a = 1
	}()
	return a
}

func DeferReturnV1() (a int) {
	a = 0
	defer func() {
		a = 1
	}()
	return a
}

//  after class

func DeferClosureLoopV1() {
	for i := 0; i < 10; i++ {
		fmt.Printf("this is in for loop ---> addr = %p, i = %d \n", &i, i)
		defer func() {
			fmt.Printf("inner defer ---> addr = %p, i = %d\n", &i, i)
		}()
	}
}

func DeferClosureLoopV2() {
	for i := 0; i < 10; i++ {
		fmt.Printf("this is in for loop ---> addr = %p, i = %d \n", &i, i)
		defer func(val int) {
			fmt.Printf("inner defer ---> addr = %p, i = %d\n", &i, i)
			println(val)
		}(i)
	}
}

func DeferClosureLoopV3() {
	for i := 0; i < 10; i++ {
		j := i
		fmt.Printf("this is in for loop ---> addr = %p, i = %d \n",&j,j)
		defer func() {
			fmt.Printf("inner defer ---> addr = %p, i = %d\n",&j,j)
			println(j)
		}()
	}
}
